package com.junjie.checkin.service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.junjie.checkin.entity.*;
import com.junjie.checkin.entity.Enum.GIftStatusEnum;
import com.junjie.checkin.entity.Enum.PointRecordTypeEnum;
import com.junjie.checkin.exception.GiftAlreadyRemoveException;
import com.junjie.checkin.exception.OperationsBeyondPermissionException;
import com.junjie.checkin.exception.ResourceNotFountException;
import com.junjie.checkin.exception.exchange.GiftUnderStockException;
import com.junjie.checkin.exception.exchange.InsufficientPointsException;
import com.junjie.checkin.mapper.*;
import com.junjie.checkin.request.gift.*;
import com.junjie.checkin.response.PageResult;
import com.junjie.checkin.response.admin.AdminGiftResponse;
import com.junjie.checkin.response.auth.AdminGiftDetailsResponse;
import com.junjie.checkin.response.front.GiftDetailsFrontResponse;
import com.junjie.checkin.response.front.GiftFrontResponse;
import com.junjie.checkin.security.service.JwtService;
import com.junjie.checkin.security.service.impl.JwtServiceImpl;
import com.junjie.checkin.utils.DateTimeFormat;
import com.junjie.checkin.websocket.entity.StompMessage;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author 洪浚杰
 * @description
 * @date 2025/6/16 09:27
 */
@Service
public class GiftService {
    @Autowired
    UserMapper userMapper;
    @Autowired
    GiftMapper giftMapper;
    @Autowired
    AddressMapper addressMapper;
    @Autowired
    StudentGiftMapper studentGiftMapper;
    @Autowired
    PointRecordMapper  pointRecordMapper;
    @Autowired
    JwtServiceImpl jwtService;
    @Autowired
    SimpMessagingTemplate simpMessagingTemplate;

    /**
     * 添加礼物
     * @param giftRequest 添加礼物的数据
     * @param token 令牌
     * @return 添加的礼物
     */
    public AdminGiftResponse insertGift(GiftRequest giftRequest, String token){
        String username = jwtService.analyzeToken(token).getUser().getUsername();
        TGift gift = new TGift();
        gift.setImageUrl(giftRequest.getImage_url());
        BeanUtils.copyProperties(giftRequest,gift);
        gift.setCreateBy(username);
        gift.setUpdateBy(username);
        giftMapper.insert(gift);
        AdminGiftResponse giftResponse = new AdminGiftResponse();
        BeanUtils.copyProperties(gift,giftResponse);
        giftResponse.setCreate_time(DateTimeFormat.dateToString(gift.getCreateTime()));
        giftResponse.setUpdate_time(DateTimeFormat.dateToString(gift.getUpdateTime()));
        return giftResponse;
    }

    /**
     * 修改礼物
     * @param giftRequest  修改的礼物数据
     * @param token 令牌
     * @param id 礼物的id
     */
    public void updateGift(GiftRequest giftRequest, String token,  Integer id) {
        String username = jwtService.analyzeToken(token).getUser().getUsername();
        TGift gift = giftMapper.selectById(id);
        if (Objects.isNull( gift)){
            throw new ResourceNotFountException();
        }
        gift.setImageUrl(giftRequest.getImage_url());
        BeanUtils.copyProperties(giftRequest,gift);
        gift.setUpdateBy( username);
        if (gift.getStatus() == GIftStatusEnum.REMOVE){
            throw new GiftAlreadyRemoveException();
        }
        // 判断礼物状态是否发生改变
        if ( gift.getStatus() == GIftStatusEnum.SELL_OUT  && giftRequest.getInventory()>0){
            gift.setStatus(GIftStatusEnum.PUT_ON);
        }
        if (gift.getStatus() == GIftStatusEnum.PUT_ON && giftRequest.getInventory()==0){
            gift.setStatus(GIftStatusEnum.SELL_OUT);
        }
        giftMapper.updateById(gift);
    }

    /**
     * 下架礼物
     * @param id 礼物id
     * @param token 令牌
     */
    public void deleteGift(Integer id,String token){
        String username = jwtService.analyzeToken(token).getUsername();
        TGift gift = giftMapper.selectById(id);
        if (Objects.isNull( gift)){
            throw  new ResourceNotFountException();
        }
        gift.setStatus(GIftStatusEnum.REMOVE);
        gift.setUpdateBy(username);
        giftMapper.deleteById(gift);
    }

    /**
     * 获取礼物列表
     * @param request 分页参数
     * @return 礼物列表
     */
    public PageResult<AdminGiftResponse> getGifts(GiftPageRequest request){
        PageHelper.startPage(request.getPage(),request.getPageSize());
        Page<TGift> giftPage = giftMapper.pageQueryAdmin(request.getStatus(), request.getName());
        List<AdminGiftResponse> responseList = giftPage.stream()
                .map(gift -> {
                    AdminGiftResponse response = new AdminGiftResponse();
                    BeanUtils.copyProperties(gift, response);
                    response.setCreate_time(DateTimeFormat.dateToString(gift.getCreateTime()));
                    response.setUpdate_time(DateTimeFormat.dateToString(gift.getUpdateTime()));
                    return response;
                })
                .collect(Collectors.toList());
        return new PageResult<>(giftPage.getTotal(),responseList);
    }

    /**
     * 获取礼物详情
     * @param id 礼物id
     * @return 礼物详情数据
     */
    public AdminGiftDetailsResponse getGiftById(Integer id){
        TGift  gift = giftMapper.selectById(id);
        if (Objects.isNull(gift)){
            throw new ResourceNotFountException();
        }
        AdminGiftDetailsResponse response = new AdminGiftDetailsResponse();
        BeanUtils.copyProperties(gift,response);
        response.setCreateTime(DateTimeFormat.dateToString(gift.getCreateTime()));
        response.setUpdateTime(DateTimeFormat.dateToString(gift.getUpdateTime()));
        return response;
    }

    /**
     * 获取前台礼物列表
     * @param pageRequest 分页参数
     * @return  礼品分页数据
     */
    public PageResult<GiftFrontResponse> getFrontGiftList(GiftFrontPageRequest pageRequest){
        PageHelper.startPage(pageRequest.getPage(),pageRequest.getPageSize());
        Page<TGift> page = giftMapper.pageQuery(pageRequest.getName());
        List<GiftFrontResponse> responseList = page.stream().map(gift -> {
            GiftFrontResponse response = new GiftFrontResponse();
            BeanUtils.copyProperties(gift,response);
            return  response;
        }).toList();
        return new PageResult<GiftFrontResponse>(page.getTotal(),responseList);
    }

    /**
     * 获取前台礼物详情
     * @param id 礼物id
     * @return 礼物详情数据
     */
    public GiftDetailsFrontResponse getFrontGiftById(Integer id){
        //  获取礼物详情
        TGift gift = giftMapper.selectById(id);
        // 判断礼物是否存在
        if (Objects.isNull(gift)){
            throw new ResourceNotFountException();
        }
        GiftDetailsFrontResponse response = new GiftDetailsFrontResponse();
        BeanUtils.copyProperties(gift,response);
        response.setDescription(gift.getDescription());
        return response;
    }


    // 兑换礼物 TODO 逻辑未完成,地址还没填写
    public void exchangeGift(Integer id, ExchangeAddressRequest address, String token){
        Integer userId = jwtService.analyzeToken(token).getUser().getId();
        TUser user = userMapper.selectById(userId);
        Integer score = user.getScore();
        String username = user.getUsername();

        // 获取礼物详情
        TGift gift = giftMapper.selectById(id);
        // 判断礼物是否存在
        if (Objects.isNull(gift)){
            throw new ResourceNotFountException();
        }
        //  判断积分是否充足
        if (score < gift.getPoint()){
            throw new InsufficientPointsException();
        }
        // 检查库存是否充足
        if (gift.getInventory() < 1){
            gift.setStatus(GIftStatusEnum.SELL_OUT);
            giftMapper.updateById(gift);
            throw new GiftUnderStockException();
        }
        try {
            // 修改库存
            int inventory = gift.getInventory()-1;
            gift.setInventory(inventory);
            // 检查库存，如果库存为0，则将礼物状态改为售罄
            if (inventory == 0){
                gift.setStatus(GIftStatusEnum.SELL_OUT);
            }
            giftMapper.updateById(gift);
            // 更新兑换记录
            TStudentGift studentGift = new TStudentGift();
            studentGift.setUserId(userId);
            studentGift.setStudentName(user.getNickname());
            studentGift.setStudentId(user.getUsername());
            studentGift.setGiftId(gift.getId());
            studentGift.setGiftName(gift.getName());
            studentGift.setImageUrl(gift.getImageUrl());
            studentGift.setPoint(gift.getPoint());
            studentGift.setName(address.getName());
            studentGift.setAddress(address.getAddress());
            studentGift.setPhone(address.getPhone());
            studentGift.setCreateBy(username);
            studentGift.setUpdateBy(username);
            studentGiftMapper.insert(studentGift);
            // 更新用户积分明细
            TPointRecord pointRecord = new TPointRecord();
            pointRecord.setUserId(userId);
            pointRecord.setRelatedType(PointRecordTypeEnum.GIFT);
            pointRecord.setRelatedId(studentGift.getId());
            pointRecord.setChangePoint(-gift.getPoint());
            Integer totalPoint = user.getScore()-gift.getPoint();
            pointRecord.setTotalPoint(totalPoint);
            pointRecord.setRemark("兑换礼品");
            pointRecord.setCreateBy(username);
            pointRecordMapper.insert(pointRecord);
            // 更新用户积分
            user.setScore(totalPoint);
            userMapper.updateById(user);
            // 构建STOMP消息
            StompMessage<TStudentGift> stompMessage = new StompMessage<>("giftExchange","兑换礼品数据更新",studentGift);
            simpMessagingTemplate.convertAndSend("/topic/admin/gift",stompMessage);
        }catch (Exception e){
            throw e;
        }


    }

}
